package com.robot.console.core;

import com.go.core.Message;
import com.robot.console.client.Client;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;

import static com.google.common.base.Preconditions.checkNotNull;

public class ClientMessageHandler extends IdleStateAwareChannelHandler
{
	public final static String CHANNEL_CONNECT = "0";
	public final static String CHANNEL_DISCONNECT = "1";
	private final Client endPoint;

	public ClientMessageHandler(Client endPoint)
	{
		checkNotNull(endPoint);

		this.endPoint = endPoint;
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception
	{
		Channel channel = ctx.getChannel();
		endPoint.channelStateChanged(CHANNEL_CONNECT, channel);
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception
	{
		Channel channel = ctx.getChannel();
		endPoint.channelStateChanged(CHANNEL_DISCONNECT, channel);
	}

	@Override
	public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception
	{
		IdleState state = e.getState();
		endPoint.channelIdleState(state);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception
	{
		Throwable cause = e.getCause();
		endPoint.channelExceptionCaught(cause);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception
	{
		try
		{
			Message message = (Message) e.getMessage();
			// Message message = null;
			// ChannelBuffer channelBuffer = (ChannelBuffer) e.getMessage();
			// int limit = channelBuffer.readableBytes();
			// if (limit > 1)
			// {
			// byte[] bytes = new byte[limit];
			// channelBuffer.readBytes(bytes);
			// message = this.endPoint.decodeToMessage(bytes);
			// }

			if (message != null)
			{
				endPoint.messageReceived(message);
			}

		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}

	}

	@Override
	public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception
	{

	}
}
